import { globalShortcut, ipcMain } from 'electron'
import { getWindow } from '../utils'
import type { BrowserWindow, IpcMainInvokeEvent } from 'electron'

const shortcutKeyConfig: Record<WindowType, string> = {
  search: '',
  manager: '',
}

export function register () {
  ipcMain.handle('shortcut', (
    _event: IpcMainInvokeEvent,
    type: WindowType,
    shortcutKey: string,
  ) => {
    if (
      shortcutKeyConfig[type] &&
      globalShortcut.isRegistered(shortcutKeyConfig[type])
    ) {
      globalShortcut.unregister(shortcutKeyConfig[type])
    }
    shortcutKeyConfig[type] = shortcutKey

    const win = getWindow(type)

    switch (type) {
      case 'search':
        return registerSearchShortcutKey(win, shortcutKey)
      case 'manager':
        return registerManagerShortcutKey(win, shortcutKey)
    }
  })
}

function registerSearchShortcutKey (win: BrowserWindow, shortcutKey: string) {
  return globalShortcut.register(shortcutKey, () => {
    if (win.isVisible()) {
      win.hide()
    } else {
      // const mousePoint = screen.getCursorScreenPoint();
      // const { width } = win.getBounds()
      // win.setPosition(mousePoint.x - width / 2, mousePoint.y);
      win.show()
    }
  })
}

function registerManagerShortcutKey (win: BrowserWindow, shortcutKey: string) {
  return globalShortcut.register(shortcutKey, () => {
    if (win.isVisible()) {
      win.hide()
    } else {
      win.show()
    }
  })
}

export function unregister () {
  globalShortcut.unregisterAll()
}
